<template>
  <el-container class="app-container">
    <el-header>
      <el-form inline>
        <el-form-item>
          <el-button class="el-icon-arrow-left" type="success" @click="prevPath">返回</el-button>
        </el-form-item>
        <el-form-item>
          <el-select v-model="pathInfo.current" style="width: 25vw;">
            <el-option v-for="(path, index) of pathInfo.list" :key="'path' + index" :label="path" :value="path" />
          </el-select>
        </el-form-item>
        <el-form-item><el-button icon="el-icon-collection" @click="selectPath">选择</el-button></el-form-item>
        <!--文件类型 目录或者文件-->
        <!--<el-form-item>
          <el-select v-model="dirType">
            <el-option label="目录和文件" value="0" />
            <el-option label="只显示文件" value="1" />
            <el-option label="只显示目录" value="2" />
          </el-select>
        </el-form-item>-->
        <el-form-item><el-button type="default" icon="el-icon-delete-solid" @click="removeProject">移除管理</el-button></el-form-item>
        <el-form-item>
          <el-select v-model="uploadType" style="width: 150px;">
            <el-option label="所有文件" value="2" />
            <el-option label="待上传文件" value="0" />
            <el-option label="已上传文件" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item><el-button type="primary" icon="el-icon-upload" size="mini" @click="multiUpload">批量上传</el-button></el-form-item>
        <el-form-item><el-button type="primary" icon="el-icon-edit" size="mini" @click="multiSetNote">批量备注</el-button></el-form-item>
      </el-form>
    </el-header>
    <el-main class="flex">
      <set-dir :on-change="changePath"></set-dir>
      <el-table ref="fileTable" :data="showFiles" class="flex-1" max-height="600px" @row-click="clickRow">
        <el-table-column type="selection" label="序号" :selectable="(row,index) =>{return row.percent !== 100}" />
        <el-table-column label="" width="60">
          <template slot-scope="{row}">
            <img v-if="['png', 'jpg', 'jpeg'].indexOf(row.ext) >= 0" class="thumb-img" src="/static/mime/tu.png" :alt="row.name" />
            <img v-else-if="exts.indexOf(row.ext) >= 0" class="thumb-img" :src="'/static/mime/' + row.ext + '.png'" :alt="row.name" />
            <img v-else-if="row.isDir" class="thumb-img" src="/static/mime/dir.png" :alt="row.name" />
            <img v-else class="thumb-img" src="/static/mime/file.png" :alt="row.name" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column label="预览图">
          <template slot-scope="{row}">
            <img v-if="['png', 'jpg', 'jpeg'].indexOf(row.ext) >= 0" class="thumb-data" :src="row.path" :alt="row.name" />
          </template>
        </el-table-column>
        <el-table-column label="大小" prop="size" width="100" />
        <el-table-column label="备注">
          <template slot-scope="{row}">
            <el-input v-if="!row.isDir" v-model="row.note" type="textarea" @change="setNote(row.id)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="{row}">
            <img v-if="row.percent === 100" src="/static/yes.png" alt="" style="width: 30px;" />
            <div>
              <el-progress v-if="row.percent < 100 " :text-inside="true" :percentage="row.percent" :stroke-width="24" status="success" style="width:100px;display: inline-block;" />
              <el-button v-if="row.percent < 100 && row.uploading === false" type="primary" size="mini" icon="el-icon-upload" @click="upload(row.id)">上传</el-button>
              <el-button v-if="row.percent < 100 && row.uploading === true" type="info" size="mini" icon="el-icon-close" @click="cancelUpload(row.id)">暂停</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <!--选择目录弹框-->
      <el-dialog ref="setPathDialog" :visible.sync="showSetPathDialog">
        <el-form inline>
          <el-form-item label="选择目录">
            <el-input type="file" />
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-footer>
  </el-container>
</template>

<script>
import path from 'path'
const { remote } = require('electron')
const fs = require('fs')
const storage = require('electron-json-storage')
const crypto  = require('crypto')

import file from '@/utils/file'
import appPath from '@/utils/app'
import { hash256 } from '@/utils/tools'
import upload from '@/utils/upload'
import db from '@/utils/db'

import SetDir from '@/views/upload/components/SetDir'


export default {
  name: 'Upload',
  components: { SetDir },
  data() {
    return {
      exts:['exe', 'zip', 'mp4', 'mp3'],
      hiddenFiles: ['sd'],
      showSetPathDialog: false,
      pathInfo:{
        current: '',
        list: []
      },
      files: [],
      uploadType: "2",
      dirType: "0",
      uploadPath: '',
    }
  },
  computed: {
    showFiles() {
      let uploadType = this.uploadType * 1
      if (uploadType === 2) {
        return this.files
      }

      let files = []
      for (let file of this.files) {
        if (uploadType === 0 && file.percent < 100) {
          files.push(file)
        } else if (uploadType === 1 && file.percent === 100) {
          files.push(file)
        }
      }
      return files
    }
  },
  watch: {
    "pathInfo.current"() {
      this.browseFolder()
    }
  },
  created() {
    console.log('upload被创建了')
    this.getPathInfo()
  },
  destroyed() {
    db.close()
  },
  methods: {
    /**
     * 流程说明
     * 1.选择目录-》2.检查是否GIT项目
     * 非GIT项目 1.遍历所有文件
     * 是GIT项目 1.设置GIT-》2.获取未提交文件
     */
    init() {
      this.getPathInfo()
    },
    /*选择目录*/
    selectPath() {
      file.selectDir().then(res => {
        this.pathInfo.current = res
      }).catch(() => {})
    },
    /*遍历目录文件*/
    browseFolder() {
      // 建立数据库句柄
      db.init(this.pathInfo.current)
      // 创建文件目录
      db.createFileTable().then(async () => {
        // 缓存目录
        await appPath.setProjectPath(this.pathInfo.current)
        // 扫描文件列表
        await this.scanFiles(this.pathInfo.current)
      })
    },
    /*扫描文件*/
    async scanFiles(path) {
      const fileInfo = await file.scanDir(path)
      let onlyFiles = fileInfo.files
      let onlyDirs = fileInfo.dirs
      switch (this.dirType) {
        case '2': onlyFiles = []; break
        case '1': onlyDirs = []; break
      }
      const files = onlyFiles
      // 去除隐藏文件
      for (const key in files) {
        let f = files[key]
        if (this.hiddenFiles.indexOf(f.ext) > -1 || f.ext === '') {
          files.splice(key, 1)
        }
      }

      // 获取缓存文件
      const sql = `SELECT * FROM files`
      db.db.all(sql, (error, rows) => {
        let caches = {}
        rows = rows === null ? [] : rows

        for (let row of rows) {
          caches[hash256(row.path)] = row
        }
        const dirLen = onlyDirs.length
        for (let key in files) {
          let file = files[key]
          let hash = hash256(file.path)
          let hasFile = typeof caches[hash] !== 'undefined'
          let cacheFile = hasFile ? caches[hash] : null
          file.upload = hasFile ? cacheFile.upload : 0
          file.total = hasFile ? cacheFile.total : 1
          file.percent = hasFile ? parseInt(file.upload / file.total * 100) : 0
          file.note = hasFile ? cacheFile.note : ''
          file.uploading = false
          file.id = Number(key)  + dirLen
          files[key] = file

          if (!hasFile) {
            upload.initProgress(file.path)
          }
        }
        this.files = onlyDirs.concat(files)
        console.log(this.files)
      })
    },
    // 移除管理
    removeProject() {
      this.$confirm('确定移除吗').then(res => {
        appPath.removeGitProject(this.pathInfo.current)
        setTimeout(this.getPathInfo, 1000)
      }).catch(() => {})
    },
    async getPathInfo() {
      this.pathInfo.current =  appPath.getLastProjectPath()
      this.pathInfo.list =  appPath.getProjectPath()
      console.log(this.pathInfo)
    },
    // 上传
    upload(index) {
      let file = this.files[index]

      // 必须选择一个目录
      if (!this.uploadPath) {
        return this.$message.error('请选择一个上传目录')
      }

      // 目录不能上传
      if (file.isDir) {
        return false
      }

      if (file.percent === 0) {
        file.percent = 10 // 一个假进度，为了看起来是立刻反应的
      }
      file.uploading = true
      this.files[index] = file
      upload.send(file.path, this.uploadPath,(percent) => {
        this.files[index].percent = percent
        if (percent === 100) {
          this.files[index].uploading = false
        }
      })
    },
    multiUpload() {
      // 获取已经选中的
      if (!this.uploadPath) {
        return this.$message.error('请选择一个上传目录')
      }
      const rows = this.$refs.fileTable.selection
      rows.forEach(row => {
        if (row.percent < 100) {
          this.upload(row.id)
        }
      })
    },
    cancelUpload(index) {
      this.files[index].uploading = false
      upload.cancel(this.files[index].path)
    },
    // 批量备注
    multiSetNote(index) {

    },
    // 文件备注
    setNote(index) {
      const file = this.files[index]
      upload.setNote(file.path, file.note)
    },
    changePath(path) {
      this.uploadPath = path
    },
    clickRow(row, event, column) {
      if (row.isDir) {
        this.pathInfo.current = this.pathInfo.current + '\\' + row.name
        setTimeout(this.getPathInfo,2000)
      }
    },
    prevPath() {
      let dir = path.dirname(this.pathInfo.current)
      this.pathInfo.current = dir
      setTimeout(this.getPathInfo,2000)
    }
  }
}
</script>

<style scoped lang="scss">
  .thumb-data{
    width: 50px;
    height:50px;
  }
  .thumb-img{
    height: 30px;
  }
</style>
